package com.ruoyi.system.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Objects;

import static com.ruoyi.common.utils.StringUtils.isEmpty;

/**
 * @Desc JWT工具类
 **/
@Slf4j
public class JwtUtil {

	// Token过期时间30分钟（用户登录过期时间是此时间的两倍，以token在reids缓存时间为准）
	public static final long EXPIRE_TIME = 30 * 60 * 1000;

	/**
	 * 校验token是否正确
	 *
	 * @param token  密钥
	 * @param secret 用户的密码
	 * @return 是否正确
	 */
	public static boolean verify(String token, String username, String secret) {
		try {
			// 根据密码生成JWT效验器
			Algorithm algorithm = Algorithm.HMAC256(secret);
			JWTVerifier verifier = JWT.require(algorithm).withClaim("userNo", username).build();
			// 效验TOKEN
			DecodedJWT jwt = verifier.verify(token);
			return true;
		} catch (Exception exception) {
			return false;
		}
	}

	/**
	 * 获得token中的信息无需secret解密也能获得
	 *
	 * @return userNo
	 */
	public static String getUserNo(String token) {
		try {
			DecodedJWT jwt = JWT.decode(token);
			return jwt.getClaim("userNo").asString();
		} catch (JWTDecodeException e) {
			return null;
		}
	}

	/**
	 * 获得token中的信息无需secret解密也能获得
	 *
	 * @return userName
	 */
	private static String getUserName(String token) {
		try {
			DecodedJWT jwt = JWT.decode(token);
			return jwt.getClaim("username").asString();
		} catch (JWTDecodeException e) {
			return null;
		}
	}

	/**
	 * 从令牌中获取用户名
	 *
	 * @param token 令牌
	 * @return 用户名
	 */
	public static String getUsernameFromToken(String token)
	{
		Claims claims = parseToken(token);
		return claims.getSubject();
	}

	/**
	 * 从令牌中获取数据声明
	 *
	 * @param token 令牌
	 * @return 数据声明
	 */
	private static Claims parseToken(String token)
	{
		return Jwts.parser()
				.setSigningKey("abcdefghijklmnopqrstuvwxyz")
				.parseClaimsJws(token)
				.getBody();
	}


	/**
	 * 获得token中的信息无需secret解密也能获得
	 *
	 * @return id
	 */
	private static Long getId(String token) {
		try {
			DecodedJWT jwt = JWT.decode(token);
			String id = jwt.getClaim("userId").asString();
			return Long.parseLong(id);
		} catch (JWTDecodeException e) {
			return null;
		}
	}


	/**
	 * 获得token中的信息无需secret解密也能获得
	 *
	 * @return phone
	 */
	private static String getUserPhone(String token) {
		try {
			DecodedJWT jwt = JWT.decode(token);
			String phone = jwt.getClaim("phone").asString();
			return phone;
		} catch (JWTDecodeException e) {
			return null;
		}
	}

	/**
	 * 生成签名,5min后过期
	 *
	 * @param userNo 用户编号
	 * @param secret   用户的密码
	 * @return 加密的token
	 */
	public static String sign(String userNo, String userName,String phone,Long userId,String secret) {
		Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
		Algorithm algorithm = Algorithm.HMAC256(secret);
		// 附带username信息
		return JWT.create()
				.withClaim("userNo", userNo)
				.withClaim("userName",userName)
				.withClaim("phone",phone)
				.withClaim("userId",userId)
				.withExpiresAt(date)
				.sign(algorithm);

	}

	/**
	 * 根据request中的token获取用户账号
	 * 
	 * @param request
	 * @return
	 */
	public static String getUserNoByToken(HttpServletRequest request){
		String accessToken = request.getHeader("Authorization");
		String userNo = getUserNo(accessToken);
		if (isEmpty(userNo)) {
			throw new RuntimeException("未获取到用户");
		}
		return userNo;
	}

	public static Long getUserIdByToken(HttpServletRequest request){
		String accessToken = request.getHeader("Authorization");
		Long id = getId(accessToken);
		if (id == null) {
			throw new RuntimeException("未获取到用户");
		}
		return id;
	}

	public static String getUserNameByToken(HttpServletRequest request){
		String accessToken = request.getHeader("Authorization");
		log.info("accessToken = " + accessToken);
		String usernameFromToken1 = JwtUtil.getUsernameFromToken(accessToken);
		log.info("usernameFromToken1 = " + usernameFromToken1);
		String userName = getUserName(accessToken);
		if (isEmpty(userName)) {
			throw new RuntimeException("未获取到用户");
		}
		return userName;
	}


	public static String getUserPhoneByToken(HttpServletRequest request){
		String accessToken = request.getHeader("Authorization");
		String userPhone = getUserPhone(accessToken);
		if (isEmpty(userPhone)) {
			throw new RuntimeException("未获取到用户");
		}
		return userPhone;
	}

	public static HttpServletRequest getRequest() {
		return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
	}

	public static void main(String[] args) {
		String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJwaG9uZSI6IiIsInVzZXJObWFtZSI6ImFkbWluIiwidXNlck5vIjoiT0lLN1RFNE0iLCJpZCI6MSwiZXhwIjoxNjA2NDY3MzQ4fQ.nSYG-FrerHLIwUvBZABZxj2GESwsL8ySLlVtrS9nDi4";
		System.out.println(JwtUtil.getUserNo(token));
		System.out.println(JwtUtil.getUserName(token));
		System.out.println(JwtUtil.getUserPhone(token));
		System.out.println(JwtUtil.getId(token));
	}
}
